
import MetaTrader5 as mt5
from datetime import datetime

from mt5utils.mql5_utils import mql5_utils
from utils.time_util import fmt_d, YYYYMMDDHHMMSS

mqlUtils = mql5_utils()

class trade_utils:
    orderSendType=False

    def singleOrder(self,status, symbol=""):
        """
        当前订单唯一性
        status=1:买
        status=2:卖
        """
        
        if self.orderSendType is False:
            self.orderSendType=True

            orderCount=mt5.orders_total()
            history_orders=mt5.history_orders_get(datetime(2020,1,1), datetime.now(), group=symbol)
            if orderCount==0 and len(history_orders)==0:
                self.sendOrder(status=status,symbol=symbol)
                return
            
            if orderCount==0 and len(history_orders)!=0:
                newster=history_orders[len(history_orders)-1]
                if newster.type==0 and status==1:
                    self.sendOrder(status=status,symbol=symbol)
                    return
                
                if newster.type==1 and status==2:
                    self.sendOrder(status=status,symbol=symbol)
                    return


    def sendOrder(self, status, symbol=""):
        """
        下单
        status=1:买
        status=2:卖
        """
        profit = 3  # 利润
        price = 0
        type = 0
        slPrice = 0
        tpPrice = 0

        if status == 1:
            type = mt5.ORDER_TYPE_BUY
            price = mqlUtils.getCurrentInfo(symbol=symbol).bid
            tpPrice = price + profit
            slPrice = price - profit * 10

        if status == 2:
            type = mt5.ORDER_TYPE_SELL
            price = mqlUtils.getCurrentInfo(symbol=symbol).ask
            tpPrice = price - profit
            slPrice = price + profit * 10

        request = {
            "action": mt5.TRADE_ACTION_DEAL,
            "symbol": symbol,
            "volume": 0.01,
            "type": type,
            "price": price,
            "sl": slPrice,
            "tp": tpPrice,
            "magic": 234000,
            "comment": "python script open",
            "type_time": mt5.ORDER_TIME_GTC,
            "type_filling": mt5.ORDER_FILLING_FOK
        }
        result = mt5.order_send(request)
        if result != None:
            self.orderSendType=False
        else:
            self.orderSendType=False